<script setup lang="ts">
import { AddCircleIcon, Edit2Icon, MinusCircleIcon } from 'tdesign-icons-vue-next';
import { ref } from 'vue';
import { rules } from '@/soar';
import LgModal from '@/soar/components/LgModal/index.vue';

const props = defineProps<{
  data: any[];
  getaway?: boolean;
}>();

const modalRef = ref();
const formRef = ref();

function ok({ data }) {
  formRef.value.validate().then((res: boolean) => {
    if (res === true) {
      if (props.getaway) {
        data.event = 'take';
      }
      const index = props.data.indexOf(data);
      if (index === -1) {
        props.data.push(data);
      } else {
        props.data[index] = data;
      }
      modalRef.value.close();
    }
    throw res;
  });
}
</script>

<template>
  <table class="gl-table">
    <tr>
      <th v-if="!getaway">事件</th>
      <th>类型</th>
      <th>值</th>
      <th style="width: 80px">
        <a class="gl-hover" @click="modalRef.open({ isExpression: true })">
          <add-circle-icon style="color: var(--app-color-primary)" size="22" />
        </a>
      </th>
    </tr>
    <tr v-for="x in data" :key="x.listener">
      <td v-if="!getaway">{{ x.event === 'start' ? '开始' : '结束' }}</td>
      <td>{{ x.isExpression ? 'expression' : 'class' }}</td>
      <td>{{ x.value }}</td>
      <td>
        <a class="gl-hover" @click="modalRef.open(x)">
          <edit2-icon style="color: var(--app-color-primary)" size="20" />
        </a>
        <a class="gl-hover gl-ml" @click="data.splice(i, 1)">
          <minus-circle-icon style="color: var(--app-color-primary)" size="20" />
        </a>
      </td>
    </tr>
  </table>
  <lg-modal ref="modalRef" header="节点监听器" width="600" v-slot="{ data }" @confirm="ok">
    <t-form ref="formRef" :data="data" label-align="top">
      <t-form-item v-if="!getaway" label="事件" name="event" :rules="rules.required('请选择事件')">
        <t-radio-group v-model="data.event">
          <t-radio value="start">开始</t-radio>
          <t-radio value="end">结束</t-radio>
        </t-radio-group>
      </t-form-item>
      <t-form-item label="类型" name="isExpression" :rules="rules.required('请选择类型')">
        <t-radio-group v-model="data.isExpression">
          <t-radio :value="true">expression</t-radio>
          <t-radio :value="false">class</t-radio>
        </t-radio-group>
      </t-form-item>
      <t-form-item label="值" name="value" :rules="rules.required('请填写值')">
        <t-textarea v-model="data.value" />
      </t-form-item>
    </t-form>
  </lg-modal>
</template>

<style scoped lang="less"></style>
